<?php

/*
  +--------------------------------------------------------------------------
  |   Invision Power Board
  |   =============================================
  |   by Matthew Mecham
  |   (c) 2001 - 2006 Invision Power Services, Inc.
  |
  |   =============================================
  |
  |
  +---------------------------------------------------------------------------
  |   > $Date: 2007-08-21 17:48:41 -0400 (Tue, 21 Aug 2007) $
  |   > $Revision: 1099 $
  |   > $Author: bfarber $
  +---------------------------------------------------------------------------
  |
  |   > PORTAL PLUG IN MODULE: Recent topics
  |   > Module written by Matt Mecham
  |   > Date started: Monday 1st August 2005 (16:22)
  +--------------------------------------------------------------------------
 */

/**
 * Portal Plug In Module
 *
 * This module displays the recently posted topic title and
 * first post.
 *
 * @package		InvisionPowerBoard
 * @subpackage	PortalPlugIn
 * @author		Matt Mecham
 * @copyright	Invision Power Services, Inc.
 * @version		2.1
 */
/**
 * Portal Plug In Module
 *
 * This module displays the recently posted topic title and
 * first post.
 * Each class name MUST be in the format of:
 * ppi_{file_name_minus_dot_php}
 *
 * @package		InvisionPowerBoard
 * @subpackage	PortalPlugIn
 * @author		Matt Mecham
 * @copyright	Invision Power Services, Inc.
 * @version		2.1
 */
if (!defined('IN_IPB')) {
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
    exit();
}

class ppi_recent_topics {

    /**
     * IPS Global object
     *
     * @var string
     */
    var $ipsclass;

    /**
     * Array of portal objects including:
     * good_forum, bad_forum
     *
     * @var array
     */
    var $portal_object = array();

    /**
     * DKM private extra query variable
     *
     * @var string
     */
    var $priv_query;

    /* ------------------------------------------------------------------------- */
    // INIT
    /* ------------------------------------------------------------------------- */

    /**
     * This function must be available always
     * Add any set up here, such as loading language and skins, etc
     *
     */
    function init() {
        $this->priv_query = "";

        if ($this->ipsclass->member['is_mod]']) {
            $this->priv_query = " AND (t.private=0 OR t.starter_id=" . $this->ipsclass->member['id'] . " OR t.forum_id IN(" . implode(",", array_keys($this->ipsclass->member['_moderater'])) . "))";
        } else {
            $this->priv_query = " AND (t.private=0 OR t.starter_id=" . $this->ipsclass->member['id'] . ")";
        }
    }

    /* ------------------------------------------------------------------------- */

    // SHOW RECENT POSTS X added by BabyWolf
    /* ------------------------------------------------------------------------- */
    function recent_posts_discussions_last_x() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------

        $html = "";
        $limit = $this->ipsclass->vars['recent_topic_newest_post_number'] ? $this->ipsclass->vars['recent_topic_newest_post_number'] : 10;

        if (count($this->portal_object['good_forum']) > 0) {
            $qe = "t.forum_id IN(" . implode(',', $this->portal_object['good_forum']) . ") AND ";
        } else {
            return;
        }

        /* Comment by BabyWolf
          $this->ipsclass->DB->simple_construct( array( 'select' => 'tid, title, posts, starter_id as member_id, starter_name as member_name, start_date as post_date, views',
          'from'   => 'topics',
          'where'  => "$qe approved=1 and state != 'closed' and (moved_to is null or moved_to = '')",
          'order'  => 'start_date DESC',
          'limit'  => array( 0, $limit ) ) );
          $this->ipsclass->DB->simple_exec(); */
        $this->ipsclass->DB->allow_sub_select = 1;
        $this->ipsclass->DB->cache_add_query('portal_get_last_post', array('qe' => $qe,
            'private' => $this->priv_query,
            'limit' => $limit
                )
        );
        $this->ipsclass->DB->cache_exec_query();

        while ($row = $this->ipsclass->DB->fetch_row()) {
            $html .= $this->_tmpl_format_new_post($row, 30);
        }

        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_latestposts($html);
    }

    /* ------------------------------------------------------------------------- */

    // Format new post entry modified by BabyWolf
    /* ------------------------------------------------------------------------- */
    function _tmpl_format_new_post($entry, $cut) {
        // Make topic url by BabyWolf
        $entry['clean_title'] = strtolower($this->ipsclass->textcode->RemoveAccent($entry['title'], "-"));
        $entry['author_url'] = $entry['starter_uname'] ? strtolower($entry['starter_uname']) : 'topic';
        $entry['topic_url'] = $this->ipsclass->vars['board_url'] . "/" . $entry['author_url'] . "/" . $entry['clean_title'] . "." . $entry['tid'];

        $entry['title'] = strip_tags($entry['title']);
        $entry['title'] = str_replace("&#33;", "!", $entry['title']);
        $entry['title'] = str_replace("&quot;", "\"", $entry['title']);

        if (strlen($entry['title']) > $cut) {
            $entry['title'] = substr($entry['title'], 0, ($cut - 3)) . "...";
            $entry['title'] = preg_replace('/&(#(\d+;?)?)?(\.\.\.)?$/', '...', $entry['title']);
        }

        $entry['avatar'] = $this->ipsclass->get_avatar($entry['avatar_location'], $this->ipsclass->member['view_avs'], '75x75', $entry['avatar_type']);

        if ($entry['avatar']) {
            $entry['avatar'] = $this->ipsclass->compiled_templates['skin_portal']->tmpl_wrap_avatar($entry['avatar'], $entry['username']);
        }

        // Added by BabyWolf

        $entry['post'] = $this->Bw_CutString($entry['post'], 200);

        $entry['member_url'] = strtolower($entry['username']);

        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_new_post_row($entry);
    }

    /* ------------------------------------------------------------------------- */

    // SHOW RECENT DISCUSSIONS X modified by BabyWolf
    /* ------------------------------------------------------------------------- */

    function recent_topics_discussions_last_x() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------

        $html = "";
        $limit = $this->ipsclass->vars['recent_topics_discuss_number'] ? $this->ipsclass->vars['recent_topics_discuss_number'] : 5;

        if (count($this->portal_object['good_forum']) > 0) {
            $qe = "forum_id IN(" . implode(',', $this->portal_object['good_forum']) . ") AND ";
        } else {
            return;
        }

        /* 		Comment by BabyWolf
          $this->ipsclass->DB->simple_construct( array( 'select' => 'tid, title, posts, starter_id as member_id, starter_name as member_name, start_date as post_date, views',
          'from'   => 'topics',
          'where'  => "$qe approved=1 and state != 'closed' and (moved_to is null or moved_to = '')",
          'order'  => 'start_date DESC',
          'limit'  => array( 0, $limit ) ) );
          $this->ipsclass->DB->simple_exec(); */

        $this->ipsclass->DB->cache_add_query('portal_get_last_topic', array('qe' => $qe,
            'private' => $this->priv_query,
            'limit' => $limit));
        $this->ipsclass->DB->cache_exec_query();

        while ($row = $this->ipsclass->DB->fetch_row()) {
            $html .= $this->_tmpl_format_topic($row, 30);
        }

        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_latesttopics($html);
    }

    /* ------------------------------------------------------------------------- */
    // CUT THE STRING X added by BabyWolf
    /* ------------------------------------------------------------------------- */

    /**
     * Cut string with x character
     *
     * @return STRING
     */
    function Bw_CutString($string = "", $num = 20) {
        $limit = 10;
        $wraptext = ' ';
        $pattern = array('#<!--quoteo[^>]*>(.*)<!--QuoteEEnd-->#i',
            '#((?>[^\s&<>"\\-\[\]]|&[\#a-z0-9]{1,7};){' . $limit . '})(?=[^\s&/<>"\\-\[\]]|&[\#a-z0-9]{1,7};)#i');
        $replacement = array('', '$0' . $wraptext);
        $string = preg_replace($pattern, $replacement, $string);
        $string = strip_tags($string);
        if (strlen($string) > $num) {
            $result = substr($string, 0, $num); //cut string with limited number
            $position = strrpos($result, " "); //find position of last space
            if ($position)
                $result = substr($result, 0, $position); //cut string again at last space if there are space in the result above    	
            $result .= ' ...';
        }
        else {
            $result = $string;
        }
        return $result;
    }

    function most_view_topic_x() {

        $html = "";
        $limit = $this->ipsclass->vars['most_viewed_topic_number'] ? $this->ipsclass->vars['recent_topics_discuss_number'] : 20;

        if (count($this->portal_object['good_forum']) > 0) {
            $qe = "t.forum_id IN(" . implode(',', $this->portal_object['good_forum']) . ") AND ";
        } else {
            return;
        }

        $this->ipsclass->DB->simple_construct(array('select' => 't.tid,t.starter_uname, t.title',
            'from' => 'topics t',
            'where' => $qe . "t.approved=1 and t.state != 'closed' and (t.moved_to is null or t.moved_to = '') " . $this->priv_query,
            'order' => 'views DESC',
            'limit' => array(0, $limit)
                )
        );
        $this->ipsclass->DB->simple_exec();

        $count = 1;
        while ($row = $this->ipsclass->DB->fetch_row()) {
            if (($count % 2) == 0)
                $class = " class=\"none_margin_li\"";
            else
                $class = "";

            // Make topic url by BabyWolf
            $row['clean_title'] = strtolower($this->ipsclass->textcode->RemoveAccent($row['title'], "-"));
            $row['author_url'] = $row['starter_uname'] ? strtolower($row['starter_uname']) : 'topic';
            $row['topic_url'] = $this->ipsclass->vars['board_url'] . "/" . $row['author_url'] . "/" . $row['clean_title'] . "." . $row['tid'];

            $html .= "<li{$class}><a href=\"{$row['topic_url']}\">" . $row['title'] . "</a></li>";
            $count++;
        }

        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_articles_list($html);
    }

    /* ------------------------------------------------------------------------- */
    // SHOW RECENT TOPICS X modified by BabyWolf
    /* ------------------------------------------------------------------------- */

    /**
     * Show the actual topics w/post
     *
     * @return VOID
     */
    function recent_topics_last_x() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------

        $html = "";
        $attach_pids = array();
        $attach_posts = array();

        //-----------------------------------------
        // Grab articles new/recent in 1 bad ass query
        //-----------------------------------------

        $limit = intval($this->ipsclass->site_info['site_portal_article_number']) ? intval($this->ipsclass->site_info['site_portal_article_number']) : (intval($this->ipsclass->vars['recent_topics_article_max']) ? intval($this->ipsclass->vars['recent_topics_article_max']) : 6);

        if (count($this->portal_object['bad_forum']) > 0) {
            $qe = " AND t.forum_id NOT IN(" . implode(',', $this->portal_object['bad_forum']) . ") ";
        }

        if (count($this->portal_object['good_forum']) > 0) {
            $qe .= " AND t.forum_id IN(" . implode(',', $this->portal_object['good_forum']) . ") ";
        }

        if ($this->ipsclass->vars['recent_topics_article_forum']) {
            $this->ipsclass->vars['recent_topics_article_forum'] = ',' . $this->ipsclass->vars['recent_topics_article_forum'];
        }

        $this->ipsclass->DB->cache_add_query('portal_get_home_topic', array('site_id' => $this->ipsclass->site_info['site_id'],
            'qe' => $qe,
            'private' => $this->priv_query,
            'limit' => $limit
                )
        );

        $outer = $this->ipsclass->DB->cache_exec_query();

        //-----------------------------------------
        // Loop through..
        //-----------------------------------------

        while ($entry = $this->ipsclass->DB->fetch_row($outer)) {
            //-----------------------------------------
            // INIT
            //-----------------------------------------

            $bottom_string = "";
            $read_more = "";
            $top_string = "";
            $got_these_attach = 0;

            //-----------------------------------------
            // BASIC INFO
            //-----------------------------------------
            // Make topic url by BabyWolf
            $entry['clean_title'] = strtolower($this->ipsclass->textcode->RemoveAccent($entry['title'], "-"));
            $entry['author_url'] = $entry['username'] ? strtolower($entry['username']) : 'topic';
            $entry['topic_url'] = $this->ipsclass->vars['board_url'] . "/" . $entry['author_url'] . "/" . $entry['clean_title'] . "." . $entry['tid'];

            $real_posts = $entry['posts'];
            $entry['title'] = strip_tags($entry['title']);
            $entry['posts'] = $this->ipsclass->do_number_format(intval($entry['posts']));
            $entry['views'] = $this->ipsclass->do_number_format($entry['views']);

            if (!$entry['author_id']) {
                $entry['member_name'] = $this->ipsclass->vars['guest_name_pre'] . $entry['author_name'] . $this->ipsclass->vars['guest_name_suf'];
                $entry['member_id'] = 0;
            }

            //-----------------------------------------
            // LINKS
            //-----------------------------------------

            $comment_link = $this->ipsclass->compiled_templates['skin_portal']->tmpl_comment_link($entry['tid']);
            $profile_link = $this->ipsclass->make_profile_link($entry['last_poster_name'], $entry['last_poster_id']);

            /* Comment by BabyWolf
              if ( $real_posts > 0 )
              {
              $bottom_string = sprintf( $this->ipsclass->lang['article_reply'], $entry['views'], $comment_link, $profile_link );
              }
              else
              {
              $bottom_string = sprintf( $this->ipsclass->lang['article_noreply'], $entry['views'], $comment_link );
              } */

            //-----------------------------------------
            // Set up date
            //-----------------------------------------

            $this->ipsclass->vars['csite_article_date'] = $this->ipsclass->vars['csite_article_date'] ? $this->ipsclass->vars['csite_article_date'] : 'm-j-y H:i';

            //-----------------------------------------
            // Get Date
            //-----------------------------------------
            // Comment by BabyWolf
            // $entry['date'] = gmdate( $this->ipsclass->vars['csite_article_date'], $entry['post_date'] + $this->ipsclass->get_time_offset() );
            $entry['date'] = $this->ipsclass->lang['D_' . gmdate('w', $entry['post_date'] + $this->ipsclass->get_time_offset())];
            $entry['date'] .= ', ngày ' . gmdate('d', $entry['post_date'] + $this->ipsclass->get_time_offset());
            $entry['date'] .= ' tháng ' . gmdate('m', $entry['post_date'] + $this->ipsclass->get_time_offset());
            $entry['date'] .= ' năm ' . gmdate('Y', $entry['post_date'] + $this->ipsclass->get_time_offset());

            /* Comment by BabyWolf
              $top_string = sprintf(
              $this->ipsclass->lang['article_postedby'],
              $this->ipsclass->make_profile_link( $entry['member_name'], $entry['member_id'] ),
              $entry['date'],
              $entry['posts']
              ); */
            // Modify top string by BabyWolf
            $top_string = sprintf(
                    $this->ipsclass->lang['article_startedtime'], $entry['date']
            );

            // Added by BabyWolf
            $entry['author'] = $this->ipsclass->make_profile_link($entry['member_name'], $entry['member_id'], $entry['username']);

            $entry['post'] = str_replace('<br>', '<br />', $entry['post']);

            //-----------------------------------------
            // Attachments?
            //-----------------------------------------
            if ($entry['pid']) // Added by BAbyWolf
                $attach_pids[$entry['pid']] = $entry['pid'];

            //-----------------------------------------
            // Avatar
            //-----------------------------------------

            $entry['avatar'] = $this->ipsclass->get_avatar($entry['avatar_location'], $this->ipsclass->member['view_avs'], '132x132', $entry['avatar_type']);

            if ($entry['avatar']) {
                $entry['avatar'] = $this->ipsclass->compiled_templates['skin_portal']->tmpl_wrap_avatar($entry['avatar'], $entry['username']);
            }

            if ($this->ipsclass->check_perms($this->ipsclass->forums->forum_by_id[$entry['forum_id']]['download_perms']) === FALSE) {
                $this->ipsclass->vars['show_img_upload'] = 0;
            }

            //-----------------------------------------
            // View image...
            //-----------------------------------------

            if (!$this->ipsclass->member['view_img']) {
                //-----------------------------------------
                // unconvert smilies first, or it looks a bit crap.
                //-----------------------------------------

                $entry['post'] = preg_replace("#<!--emo&(.+?)-->.+?<!--endemo-->#", "\\1", $entry['post']);

                $entry['post'] = preg_replace("/<img src=[\"'](.+?)[\"'].+?" . ">/", "(IMG:<a href='\\1' target='_blank'>\\1</a>) ", $entry['post']);
            }

            $entry['member_url'] = $entry['username'] ? strtolower($entry['username']) : "member";
            if ($entry['tid'] == $this->ipsclass->vars['portal_announce'])
                $announce_html = $this->ipsclass->compiled_templates['skin_portal']->tmpl_articles_row($entry, $top_string);
            else {
                // Added by BabyWolf
                $matches = array();
                if (preg_match("/\[attachment=(.*?):(.*?)\]/s", $entry['post'], $matches)) {
                    preg_replace('/\[attachment(.*?)\]/s', "", $html);
                }

                $entry['post'] = $this->Bw_CutString($entry['post'], 500);

                //$entry = array_merge($entry, $this->ipsclass->Bw_GetCustomFields($entry));
                // Comment by BabyWolf
                // $html .= $this->ipsclass->compiled_templates['skin_portal']->tmpl_articles_row($entry, $bottom_string, $top_string);

                $html .= $this->ipsclass->compiled_templates['skin_portal']->tmpl_articles_row($entry, $top_string);
            }
        }

        // Add announcement topic at the top by BabyWolf
        $html = $announce_html . $html;

        //-----------------------------------------
        // Process Attachments
        //-----------------------------------------
        // Added by BabyWolf
        //$html = preg_replace('/\[attachment(.*?)\]/s',"",$html);

        if (count($attach_pids)) {
            if (!is_object($this->class_attach)) {
                //-----------------------------------------
                // Grab render attach class
                //-----------------------------------------

                require_once( ROOT_PATH . 'sources/classes/attach/class_attach.php' );
                $this->class_attach = new class_attach();
                $this->class_attach->ipsclass = & $this->ipsclass;
                $this->class_attach->attach_post_key = '';

                $this->ipsclass->load_template('skin_topic');
                $this->ipsclass->load_language('lang_topic');
            }

            $this->class_attach->attach_post_key = '';
            $this->class_attach->type = 'post';
            $this->class_attach->init();

            $html = $this->class_attach->render_attachments($html, $attach_pids, 'skin_portal');
        }

        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_articles($html);
    }

    /* ------------------------------------------------------------------------- */

    // Format topic entry modified by BabyWolf
    /* ------------------------------------------------------------------------- */

    function _tmpl_format_topic($entry, $cut) {
        // Make topic url by BabyWolf
        $entry['clean_title'] = strtolower($this->ipsclass->textcode->RemoveAccent($entry['title'], "-"));
        $entry['author_url'] = $entry['username'] ? strtolower($entry['username']) : 'topic';
        $entry['topic_url'] = $this->ipsclass->vars['board_url'] . "/" . $entry['author_url'] . "/" . $entry['clean_title'] . "." . $entry['tid'];

        $entry['title'] = strip_tags($entry['title']);
        $entry['title'] = str_replace("&#33;", "!", $entry['title']);
        $entry['title'] = str_replace("&quot;", "\"", $entry['title']);

        if (strlen($entry['title']) > $cut) {
            $entry['title'] = substr($entry['title'], 0, ($cut - 3)) . "...";
            $entry['title'] = preg_replace('/&(#(\d+;?)?)?(\.\.\.)?$/', '...', $entry['title']);
        }

        $entry['avatar'] = $this->ipsclass->get_avatar($entry['avatar_location'], $this->ipsclass->member['view_avs'], '75x75', $entry['avatar_type']);

        if ($entry['avatar']) {
            $entry['avatar'] = $this->ipsclass->compiled_templates['skin_portal']->tmpl_wrap_avatar($entry['avatar'], $entry['username']);
        }

        $entry['post'] = $this->Bw_CutString($entry['post'], 200);

        //$entry['posts'] = $this->ipsclass->do_number_format($entry['posts']);
        // Comment by BabyWolf
        // $entry['views'] = $this->ipsclass->do_number_format($entry['views']);
        // $this->ipsclass->vars['csite_article_date'] = $this->ipsclass->vars['csite_article_date'] ? $this->ipsclass->vars['csite_article_date'] : 'm-j-y H:i';
        // $entry['date']  = gmdate( $this->ipsclass->vars['csite_article_date'], $entry['post_date'] + $this->ipsclass->get_time_offset() );
        // Comment by BabyWolf
        // return $this->ipsclass->compiled_templates['skin_portal']->tmpl_topic_row($entry['tid'], $entry['title'], $entry['posts'], $entry['views'], $entry['member_id'], $entry['member_name'], $entry['date']);
        return $this->ipsclass->compiled_templates['skin_portal']->tmpl_topic_row($entry);
    }

}

?>